﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace 修为尽失.辅助
{
    public class Executer
    {
        public static void TryRunByAsyn(Action fun, bool skipException = true)
        {
            TryRunSkipExceptoin(() => fun.BeginInvoke(null, null), skipException);
        }

        public static void TryRunByThreadPool(Action fun, bool skipException = true)
        {
            ThreadPool.QueueUserWorkItem(obj => TryRunSkipExceptoin(fun, skipException));
        }

        public static void TryRunByTask(Action fun, bool skipException = true) => Task.Factory.StartNew(() => TryRunSkipExceptoin(fun, skipException));

        public static void TryRunByThread(Action fun, bool skipException = true)
        {
            Thread thread = new Thread(new ThreadStart(fun.Invoke));
            thread.IsBackground = true;
            if (skipException)
            {
                try
                {
                    thread.Start();
                }
                catch
                {
                }
            }
            else
                thread.Start();
        }

        public static void TryRunSkipExceptoin(Action fun, bool skipException = true)
        {
            if (skipException)
            {
                try
                {
                    fun();
                }
                catch (Exception ex)
                {
                   ex.ShowException();
                }
            }
            else
                fun();
        }

        public static void TryRunLogExceptioin(Action fun, string message = "")
        {
            try
            {
                fun();
            }
            catch (Exception ex)
            {
                
              ex.ShowException();
            }
        }

        public static void TryRunThrowExceptioin(Action fun, string message = "")
        {
            try
            {
                fun();
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format("{0}，请尝试重新运行/重启程序，或者联系技术支持。{1}错误详情:{2}", (object) message, (object) Environment.NewLine, (object) ex.ToLogString()), ex);
            }
        }
    }
}